#!/bin/bash
# auto tuyb
# time 20250312

# 执行结果判断函数
function isgreen() {
    if [ $? -eq 0 ]; then
        echo -e "\e[32m$1==========>succeed\e[0m"
    else
        echo -e "\e[31m$1==========>failed\e[0m"
        # exit 1
    fi
}

# if ! command -v sshpass &>/dev/null; then
#     echo "sshpass 未安装，正在安装..."
#     sudo apt update && sudo apt install -y sshpass
#     isgreen "安装sshpass"
# fi

# 备份远程主机的文件
backup_remote() {
    local remote_host="$1"   # 远程主机名或 IP
    local remote_user="$2"   # 远程用户
    local remote_pass="$3"   # 远程用户密码
    local remote_dir="$4"    # 远程需要备份的目录
    # echo "$1 $2 $3 $4"
    sub_dir=$(echo "$remote_dir" | awk '{gsub(/^\/|\/$/,""); print $0"/"}')
    echo "$sub_dir"
    

    local backup_dir="/backup/remote_host/$remote_host/$sub_dir"  # 本机备份目录

    # 确保 /backup 目录存在
    mkdir -p "$backup_dir"  

    # shellcheck disable=SC2129
    echo -e "\e[1;32m===============start $remote_host:$remote_dir $(date)===============\e[0m"  >> /backup/remote_backup.log 2>&1

    # 使用 sshpass 进行免交互 rsync 备份
    sshpass -p "$remote_pass" rsync -avz -e "ssh -o StrictHostKeyChecking=no" "$remote_user@$remote_host:$remote_dir" "$backup_dir/" >> /backup/remote_backup.log 2>&1
    isgreen "$remote_host:$remote_dir 备份" >> /backup/remote_backup.log 2>&1
}

# 读取配置文件
while IFS= read -r line; do
    # 跳过空行和以 # 开头的注释行
    if [[ -n "$line" && ! "$line" =~ ^# ]]; then
        host=$(echo "$line" | awk '{print $1}')
        user=$(echo "$line" | awk '{print $2}')
        pass=$(echo "$line" | awk '{print $3}')
        dir=$(echo "$line" | awk '{print $4}')
        
        backup_remote "$host" "$user" "$pass" "$dir"
        echo "-----------------------------end  $(date)-----------------------------" >> /backup/remote_backup.log 2>&1
        echo "" >> /backup/remote_backup.log 2>&1
    fi
done < backup-inventory.txt

